package com.fowo.api.service.handleWork;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.datainterface.util.k3cloud.domain.Authentication;
import com.fowo.api.datainterface.util.k3cloud.domain.BillSave;
import com.fowo.api.entity.BdDepartment;
import com.fowo.api.entity.BdRate;
import com.fowo.api.entity.BosAssistantdataDetail;
import com.fowo.api.model.ad.stream.AdStreamPublishAction;
import com.fowo.api.model.ad.stream.AdStreamVo;
import com.fowo.api.service.handleWork.jindieEntity.jindieResult;
import com.fowo.api.service.handleWork.jindieEntity.jindieVoucher2;
import com.fowo.api.service.impl.AdStreamServiceImpl;
import com.fowo.api.service.impl.BdDepartmentServiceImpl;
import com.fowo.api.service.impl.BdRateServiceImpl;
import com.fowo.api.service.impl.BosAssistantdataDetailServiceImpl;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class adStreamPublish  implements AdStreamPublishAction {

    @Resource
    private AdStreamServiceImpl adStreamService;
    @Resource
    private BosAssistantdataDetailServiceImpl bosAssistantdataDetailService;
    @Resource
    private BdDepartmentServiceImpl departmentService;
    @Resource
    private BdRateServiceImpl bdRateService;

//64e8964fb4af0d
    private static final Authentication auth=new Authentication("64e8964fb4af0d","Administrator","a@123456");

    private static final K3CloudTemplate k3loudTemplate=new K3CloudTemplate("http://121.225.97.82:8001/K3cloud/",auth);

    @Override
    public void run(List<Long> idList) throws Exception {
            for(int i=0;i<idList.size();i++){
                Long aLong = idList.get(i);
                AdStreamVo voById = adStreamService.getVoById(aLong);
                pushJIndie(voById);
            }
    }

    @Transactional(rollbackFor = Exception.class)
    public synchronized void pushJIndie(AdStreamVo voById) {
        Assert.isTrue(voById.getIsPublish().equals("否"),"已经推送了!");
        String bizhong=bizhong(voById.getCurrency());
        BdRate one = bdRateService.getOne(Wrappers.<BdRate>query()
                .lambda().eq(BdRate::getCode, bizhong));
        Assert.notNull(one,"当前类别在汇率表中不存在!");
        BigDecimal bj=one.getRateNum();
        //获取部门的信息
        BdDepartment bumen = departmentService.getOne(Wrappers.<BdDepartment>query().lambda().eq(BdDepartment::getName, voById.getDepartment()));
        Assert.notNull(bumen,"部门信息在金蝶中不存在!");
        BosAssistantdataDetail shiyebu = bosAssistantdataDetailService.getOne(Wrappers.<BosAssistantdataDetail>query().lambda().eq(BosAssistantdataDetail::getDataValue, voById.getDivision()).eq(BosAssistantdataDetail::getFid,"64005285edcec5"));
        Assert.notNull(shiyebu,"事业部信息在金蝶中不存在!");
        BosAssistantdataDetail dianpu = bosAssistantdataDetailService.getOne(Wrappers.<BosAssistantdataDetail>query().lambda().eq(BosAssistantdataDetail::getDataValue, voById.getShop()).eq(BosAssistantdataDetail::getFid,"6402dffc3586da"));
        Assert.notNull(dianpu,"店铺信息在金蝶中不存在!");

        BillSave billSave = new BillSave("GL_VOUCHER");
        jindieVoucher2 jindieVoucher=new  jindieVoucher2();
        jindieVoucher.setIsAutoAdjustField("true");
        jindieVoucher2.ModelDTO  modelDTO=new jindieVoucher2.ModelDTO();
        modelDTO.setFvoucherid(0);
        //账簿
        jindieVoucher2.ModelDTO.FAccountBookIDDTO FAccountBookIDDTO=new  jindieVoucher2.ModelDTO.FAccountBookIDDTO();
        FAccountBookIDDTO.setFNumber("002");
        modelDTO.setFAccountBookID(FAccountBookIDDTO);
        modelDTO.setFDate(voById.getJsDate());//日期
        //凭证字
        jindieVoucher2.ModelDTO.FVOUCHERGROUPIDDTO FVOUCHERGROUPIDDTO=new jindieVoucher2.ModelDTO.FVOUCHERGROUPIDDTO();
        FVOUCHERGROUPIDDTO.setFNumber("PRE001");
        modelDTO.setFvouchergroupid(FVOUCHERGROUPIDDTO);
        modelDTO.setFvouchergroupno("1");
        modelDTO.setFDocumentStatus("Z");
        List<jindieVoucher2.ModelDTO.FEntityDTO> list=new ArrayList<>();
        jindieVoucher2.ModelDTO.FEntityDTO entity = createEntity("1122.01",KeepOne(voById.getMoney(),bj).doubleValue(),null,shiyebu.getNumber(),null,dianpu.getNumber(),null,null,"冲正"+dianpu.getDataValue()+"店铺应收款",bizhong,voById.getMoney());
        //01001
        jindieVoucher2.ModelDTO.FEntityDTO entity1 = createEntity("6601.02.02",KeepOne(voById.getMoney().negate(),bj).doubleValue(),null,shiyebu.getNumber(),bumen.getNumber(),dianpu.getNumber(),null,null,"冲正"+dianpu.getDataValue()+"店铺应收款",bizhong,voById.getMoney().negate());
        jindieVoucher2.ModelDTO.FEntityDTO entity2 = createEntity("6601.02.02",KeepOne(voById.getMoney(),bj).doubleValue(),null,shiyebu.getNumber(),bumen.getNumber(),dianpu.getNumber(),null,null,"确认平台费用",bizhong,voById.getMoney());
        jindieVoucher2.ModelDTO.FEntityDTO entity3 = createEntity("1012.01",null,KeepOne(voById.getMoney(),bj).doubleValue(),shiyebu.getNumber(),bumen.getNumber(),dianpu.getNumber(),null,null,"确认平台费用",bizhong,voById.getMoney());

        list.add(entity);
        list.add(entity1);
        list.add(entity2);
        list.add(entity3);

        modelDTO.setFEntity(list);
        jindieVoucher.setModel(modelDTO);
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(jindieVoucher, false, false);
        billSave.setModel(stringObjectMap);
        String result = k3loudTemplate.executeBillSave(billSave, String.class);
        jindieResult jindieResult = JSONObject.parseObject(result, jindieResult.class);
        if(jindieResult.getResult().getResponseStatus().getIsSuccess().equals("true")){
            voById.setIsPublish("是");
        }else{
            voById.setIsPublish("否");
        }
        adStreamService.updateById(voById);
        if(!jindieResult.getResult().getResponseStatus().getIsSuccess().equals("true")){
            Assert.isTrue(false,"推送失败:"+jindieResult.getResult().getResponseStatus().getErrors().get(0).getMessage());
        }
    }

    private static jindieVoucher2.ModelDTO.FEntityDTO createEntity(String kemu,
                                                                   Double jiefang,
                                                                   Double daifang,
                                                                   String shiyebu,
                                                                   String bumen,
                                                                   String dianpu,
                                                                   String gongchang,
                                                                   String code,
                                                                   String beizhu,
                                                                   String bizhong,
                                                                   BigDecimal benbi
                                                                    ){
        jindieVoucher2.ModelDTO.FEntityDTO fEntityDTO=new jindieVoucher2.ModelDTO.FEntityDTO();
        //科目编码
        jindieVoucher2.ModelDTO.FEntityDTO.FACCOUNTIDDTO FACCOUNTIDDTO=new jindieVoucher2.ModelDTO.FEntityDTO.FACCOUNTIDDTO();
        FACCOUNTIDDTO.setFNumber(kemu);
        fEntityDTO.setFaccountid(FACCOUNTIDDTO);
        fEntityDTO.setFexplanation(beizhu);
        //币别
        jindieVoucher2.ModelDTO.FEntityDTO.FCURRENCYIDDTO  FCURRENCYIDDTO=new jindieVoucher2.ModelDTO.FEntityDTO.FCURRENCYIDDTO();
        FCURRENCYIDDTO.setFNumber(bizhong);
        fEntityDTO.setFcurrencyid(FCURRENCYIDDTO);
        //汇率
        jindieVoucher2.ModelDTO.FEntityDTO.FEXCHANGERATETYPEDTO FEXCHANGERATETYPEDTO=new jindieVoucher2.ModelDTO.FEntityDTO.FEXCHANGERATETYPEDTO();
        FEXCHANGERATETYPEDTO.setFNumber("HLTX01_SYS");
        fEntityDTO.setFexchangeratetype(FEXCHANGERATETYPEDTO);
        fEntityDTO.setFexchangerate(0.0);
        //借方金额
        fEntityDTO.setFdebit(jiefang);//
//        fEntityDTO.setFexchangerate(1.0);
        fEntityDTO.setFamountfor(benbi.doubleValue());//原币金额
//        fEntityDTO.setFAmount(jiefang!=null?jiefang:daifang);
        // 贷方金额
        fEntityDTO.setFcredit(daifang);
        jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO FDetailIDDTO=new jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO();
        //事业部
        if(shiyebu!=null){
            jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFF100003DTO  FDETAILIDFFLEX4DTO=new  jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFF100003DTO();
            FDETAILIDFFLEX4DTO.setFNumber(shiyebu);
            FDetailIDDTO.setFDETAILID__FF100003(FDETAILIDFFLEX4DTO);
            fEntityDTO.setFDetailID(FDetailIDDTO);
        }
        //部门
        if(bumen!=null){
            jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFFLEX5DTO  FDETAILIDFFLEX4DTO=new  jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFFLEX5DTO();
            FDETAILIDFFLEX4DTO.setFNumber(bumen);
            FDetailIDDTO.setFDETAILID__FFLEX5(FDETAILIDFFLEX4DTO);
            fEntityDTO.setFDetailID(FDetailIDDTO);
        }
        //店铺
        if(dianpu!=null){
            jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFF100007DTO  FDETAILIDFF100007DTO=new  jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFF100007DTO();
            FDETAILIDFF100007DTO.setFNumber(dianpu);
            FDetailIDDTO.setFDETAILID__FF100007(FDETAILIDFF100007DTO);
            fEntityDTO.setFDetailID(FDetailIDDTO);
        }
        return fEntityDTO;
    }
    //获取币种
    public  String bizhong(String s){
        String str=null;
        //金蝶的币种
        if(s.equals("USD")){
            str="PRE007";
        }else if(s.equals("CAD")){
            str="PRE008";
        }else if(s.equals("MXN")){
            str="PRE009";
        }else if(s.equals("EUR")){
            str="PRE003";
        }else if(s.equals("GBP")){
            str="PRE006";
        }else if(s.equals("CNY")){
            str="PRE001";
        }else{
            Assert.isTrue(false,"没有找到这个币种!");
        }
        return  str;

    }

    public BigDecimal KeepOne(BigDecimal bigDecimal, BigDecimal huilv){
        BigDecimal bigDecimal1 =bigDecimal.multiply(huilv).setScale(2, BigDecimal.ROUND_HALF_UP);
        return bigDecimal1;
    }

}
